﻿using UnityEngine;
using UnityEditor;
using System.Collections;


[CustomEditor(typeof(CorePlace))]
public class PlacerScript : Editor
{

    Object placeItem;

    Vector3 worldPos;

    string placeItemAssetPath = "";

    CorePlace corePlace;

	bool placingItem = false;

    public void OnEnable()
    {
        EditorApplication.update += Update;
        corePlace = (CorePlace)target;
    }

    public override void OnInspectorGUI()
    {
        EditorPrefs.SetBool("test.CanPlace", EditorGUILayout.Toggle("Placed Enabled", EditorPrefs.GetBool("test.CanPlace")));
        corePlace.alwaysShowGrid = EditorGUILayout.Toggle("Always Show Grid", corePlace.alwaysShowGrid);

        Vector3 temp = ((CorePlace)target).worldPos;
        corePlace.gridSize = EditorGUILayout.FloatField("Grid Size:", corePlace.gridSize);
        EditorGUILayout.LabelField("Object to draw:");
        Object tempItem = EditorGUILayout.ObjectField(placeItem, typeof(GameObject));

        EditorGUILayout.LabelField("Set name to empty string for default");
        EditorPrefs.SetString("placeableName", EditorGUILayout.TextField("Object Name", EditorPrefs.GetString("placeableName")));

        EditorPrefs.SetBool("parentPlacable", EditorGUILayout.Toggle("Parent Placed Object", EditorPrefs.GetBool("parentPlacable")));

        if (EditorPrefs.GetBool("parentPlacable"))
        {
            EditorGUILayout.LabelField("Make sure the name matches an object in the hierarchy");
            corePlace.parentName = EditorGUILayout.TextField("Parent Name", corePlace.parentName);
        }

        //if the set item has been changed, remember the asset path
        if(tempItem != placeItem && tempItem != null)
        {
            placeItem = tempItem;
            placeItemAssetPath = AssetDatabase.GetAssetPath(tempItem);
            EditorPrefs.SetString("placeItemAssetPath", placeItemAssetPath);
        }

        //if there is no item, see if we have an asset path to load from
        if (tempItem == null)
        {
            if (EditorPrefs.HasKey("placeItemAssetPath"))
            {
                //there's a key, so try and load
                GameObject newItem = AssetDatabase.LoadAssetAtPath(EditorPrefs.GetString("placeItemAssetPath"), typeof(GameObject)) as GameObject;
                if (newItem != null) placeItem = newItem;               
            }
        }

    }

    public void Update()
    {
        //if (SceneView.currentDrawingSceneView.camera == null) UnityEngine.Debug.Log("Is null");
        //else UnityEngine.Debug.Log(SceneView.currentDrawingSceneView.camera.transform.position.ToString());
    }

    void OnSceneGUI()
    {
        int controlID = GUIUtility.GetControlID(FocusType.Passive);

        bool doPlace = true;

        //UnityEngine.Debug.Log(Time.deltaTime.ToString());

        Vector3 modMouse = Event.current.mousePosition;
        modMouse.y = -modMouse.y + SceneView.currentDrawingSceneView.camera.pixelHeight;

        worldPos = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(modMouse);
        worldPos.z = 0;
        worldPos.x = Mathf.Round(worldPos.x);
        worldPos.x = Mathf.Floor(worldPos.x / corePlace.gridSize) * corePlace.gridSize + corePlace.gridSize / 2;
        worldPos.y = Mathf.Round(worldPos.y);
        worldPos.y = Mathf.Floor(worldPos.y / corePlace.gridSize) * corePlace.gridSize + corePlace.gridSize / 2;
        corePlace.worldPos = worldPos;

        if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && EditorPrefs.GetBool ("test.CanPlace")) 
        {
			//check for collision.  if collision don't place.
			Vector3 rayStart = worldPos;
			rayStart.z = -20;


			int layerMask = 1 << 10;
			layerMask = layerMask | 1 << 9;
			layerMask = ~layerMask;
			RaycastHit hit;
			if (Physics.Raycast (rayStart, new Vector3 (0, 0, 1), out hit, 1000, layerMask)) 
            {
				if (Event.current.keyCode != KeyCode.LeftShift) 
                {
					Debug.LogWarning ("Refusing to place item because I hit a: " + hit.collider.name);
					doPlace = false;
				}
			}
			if (doPlace) 
            {
				placingItem = true;
				GameObject temp = Instantiate (placeItem) as GameObject;
				temp.transform.position = worldPos;
				string newName = EditorPrefs.GetString ("placeableName");
				if (newName.Length > 0)
						temp.name = newName;

				if (EditorPrefs.GetBool ("parentPlacable")) 
                {
					GameObject newParent = GameObject.Find (corePlace.parentName);
					if (newParent != null) 
                    {
						temp.transform.parent = newParent.transform;
					} 
                    else 
                    {
                        UnityEngine.Debug.LogWarning ("Failed to load target parent for placed object: " + corePlace.parentName);
					}
				}
			}//end raycast hit else
		}//end left mouse event
		else if (Event.current.type == EventType.MouseUp && Event.current.button == 0) 
        {
            placingItem = false;
        }
        else if (Event.current.type == EventType.Layout)
        {
            HandleUtility.AddDefaultControl(controlID);
        }
        else if (Event.current.type == EventType.Repaint)
        {
            //Handles.color = Color.red;
            //Handles.CubeCap(0, worldPos, Quaternion.identity, 1);
        }
        else if (Event.current.type == EventType.MouseMove && Event.current.modifiers == EventModifiers.Shift)        
        {
            GameObject temp = Instantiate (placeItem) as GameObject;
			temp.transform.position = worldPos;
			string newName = EditorPrefs.GetString ("placeableName");
			if (newName.Length > 0)
					temp.name = newName;

            if (EditorPrefs.GetBool("parentPlacable"))
            {
                GameObject newParent = GameObject.Find(corePlace.parentName);
                if (newParent != null)
                {
                    temp.transform.parent = newParent.transform;
                }
                else
                {
                    UnityEngine.Debug.LogWarning("Failed to load target parent for placed object: " + corePlace.parentName);
                }
            }
        }

        SceneView.RepaintAll();
    }//end method

    
}


